const express = require("express");
var router = express.Router();
const multer = require("multer");
const db = require("../model/db");
const path = require("path");


//作者：段彦蓉
//随机数
function suiJiShu(min, max) {
    const dec = max - min;
    return parseInt(Math.random() * dec + min);
}

//作者：段彦蓉
//创建存储对象
const storage = multer.diskStorage({
    destination: path.join(__dirname, "../public/upload"),
    filename: function (req, file, cb) {
        const name = Date.now() + "" + suiJiShu(100000, 10000000) + path.extname(file.originalname);
        cb(null, name)
    }
})

//作者：段彦蓉
const upload = multer({//配置上传处理
    storage,
    fileFilter: function (req, file, cb) {
        //如何得到文件名的后缀名
        const ext = path.extname(file.originalname).toLowerCase();//得到文件的后缀名
        const expects = [".jpg", ".png", ".bmp", ".gif", ".tiff"];//服务器允许的后缀名
        if (expects.includes(ext)) {
            cb(null, true);
        } else {
            cb(new Error("文件类型不正确"));
        }
    },
    limits: {
        fileSize: 500 * 1024//文件限制在500kb以内
    }
}).array("image");

//作者：段彦蓉
//添加院线
router.post("/", async (req, res) => {
    const data = await db.Cinema.create(req.body);
    res.send(data);
})

//作者：段彦蓉,向志祥
//修改院线
router.put("/:id", async (req, res) => {
    await db.Cinema.updateOne({
        //条件对象
        _id: req.params.id
    }, req.body);
    res.send(true);
})

//作者：段彦蓉
//删除院线
router.delete("/:id", async (req, res) => {
    await db.Cinema.deleteOne(
        //条件对象
        {
            _id: db.ObjectId(req.params.id)
        });
    await db.MovieAndCinema.deleteOne({
        cinema: req.params.id
    })
    res.send(true);
})

//作者：段彦蓉,向志祥
//查询所有院线(模糊查询)
router.get("/", async (req, res) => {
    if (!req.query.field) {
        req.query.field = "_id";//默认按照_id排序
    }
    if (!req.query.sort) {
        req.query.sort = "asc";//默认按照升序排序
    }
    //拼接排序字符串
    let s = req.query.field;
    if (req.query.sort === "desc") {
        s = "-" + s;
    }
    //处理分页
    if (!req.query.page) {
        req.query.page = 1;//页索引默认为1
    }
    if (!req.query.limit) {
        req.query.limit = 10;//页容量默认为10
    }
    const page = parseInt(req.query.page);
    const limit = parseInt(req.query.limit);
    let condition = {};
    if (req.query.key) {
        const exp = new RegExp(req.query.key, "i")//不区分大小写，模糊查询的正则表达式
        condition = {
            $or: [
                { name: { $regex: exp } },
                { tel: { $regex: exp } },
                { addr: { $regex: exp } }
            ]
        };
    }
    const data = await db.Cinema.find(condition).sort(s).skip((page - 1) * limit).limit(limit);//按照课时升序排序(降序sort("-hours"))
    const count = await db.Cinema.countDocuments(condition);
    res.send({
        code: 0,
        message: "",
        count,
        data
    });
})

//作者：段彦蓉
//或得单个院线
router.get("/:id", async (req, res) => {
    const data = await db.Cinema.findById(req.params.id);
    res.send(data);
})
module.exports = router;